<template>
  <div class="chart-container">
    <div class="pie-chart" ref="pieChartRef"></div>
    <div class="bar-chart" ref="barChartRef"></div>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, onBeforeUnmount} from 'vue';
import * as echarts from 'echarts';


// 数据
const pieData = [
  { value: 30, name: '葛仙村' },
  { value: 40, name: '河红茶' },
  { value: 30, name: '野生动物园' },
];

const barData = {
  categories: ['葛仙村', '河红茶', '野生动物园'],
  series: [
    {
      name: '生态物质产品',
      data: [10, 10, 10],
      type: 'bar',
      stack: '总量',
      color: '#008080',
    },
    {
      name: '生态调节服务',
      data: [10, 10, 10],
      type: 'bar',
      stack: '总量',
      color: '#6495ED',
    },
    {
      name: '生态文化服务',
      data: [10, 10, 10],
      type: 'bar',
      stack: '总量',
      color: '#00CED1',
    },
  ],
};

// 初始化图表
const pieChartRef = ref(null);
const barChartRef = ref(null);

let barChart: echarts.ECharts | null = null;  // ECharts 实例
let pieChart: echarts.ECharts | null = null;  // ECharts 实例


onMounted(() => {
  if (pieChartRef.value) {
    const pieChart = echarts.init(pieChartRef.value);
    pieChart.setOption({
      tooltip: {
        trigger: 'item',
      },
      series: [
        {
          type: 'pie',
          radius: '50%',
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    });
  }

  if (barChartRef.value) {
    const barChart = echarts.init(barChartRef.value);
    barChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      legend: {
        data: barData.series.map((s) => s.name),
      },
      xAxis: {
        type: 'category',
        data: barData.categories,
      },
      yAxis: {
        type: 'value',
        name: '亿元',
      },
      series: barData.series,
    });
  }
});


onBeforeUnmount(
    () => {
      // 在组件销毁前执行
      // 清理图表实例
      if (barChart) {

        barChart.dispose();
        barChart = null;
      }
      if (pieChart) {

        pieChart.dispose();
        pieChart = null;
      }
    }
)
</script>

<style scoped>
.chart-container {

  display: flex;
  flex-direction: column;
  align-items: center;
}

.pie-chart {
  width: 100%;
  height: 200px;
  margin-bottom: 20px;
}

.bar-chart {
  width: 400px;
  height: 100px;
}
</style>
